package com.businesscard.system.service.impl;

import com.businesscard.system.entity.User;
import com.businesscard.system.mapper.UserMapper;
import com.businesscard.system.service.UserService;
import com.businesscard.system.util.EmailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmailUtil emailUtil;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public User login(String username, String password) {
        User user = userMapper.selectByUsername(username);

        if (user == null) {
            return null;
        }

        // 检查账户是否锁定
        if (Boolean.TRUE.equals(user.getAccountLocked())) {
            return null;
        }

        // 验证常规密码
        if (passwordEncoder.matches(password, user.getPassword())) {
            // 登录成功，重置登录尝试次数
            userMapper.updateLoginInfo(user.getId(), 0);
            return user;
        }

        // 验证临时密码
        if (user.getTemporaryPassword() != null && user.getTempPasswordExpire() != null) {
            // 检查临时密码是否过期
            Date now = new Date();
            if (!now.after(user.getTempPasswordExpire())) {
                // 检查临时密码是否匹配
                if (password.equals(user.getTemporaryPassword())) {
                    // 临时密码登录成功，重置登录尝试次数
                    userMapper.updateLoginInfo(user.getId(), 0);
                    logger.info("用户{}使用临时密码登录成功", username);
                    return user;
                }
            } else {
                logger.info("用户{}的临时密码已过期", username);
            }
        }

        // 所有验证都失败，增加登录尝试次数
        int attempts = user.getLoginAttempts() == null ? 0 : user.getLoginAttempts();
        attempts++;

        // 超过5次锁定账户
        if (attempts >= 5) {
            userMapper.updateLockStatus(user.getId(), true);
        }

        userMapper.updateLoginInfo(user.getId(), attempts);
        return null;
    }

    @Override
    @Transactional
    public boolean register(User user) {
        // 检查用户名是否已存在
        if (userMapper.selectByUsername(user.getUsername()) != null) {
            return false;
        }

        // 检查邮箱是否已存在
        if (userMapper.selectByEmail(user.getEmail()) != null) {
            return false;
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 设置默认角色
        user.setRole("USER");

        // 插入用户
        return userMapper.insert(user) > 0;
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public User getUserByEmail(String email) {
        return userMapper.selectByEmail(email);
    }

    @Override
    public List<User> getAllUsers() {
        try {
            return userMapper.selectAll();
        } catch (Exception e) {
            logger.error("获取所有用户列表失败: {}", e.getMessage(), e);
            return Collections.emptyList();
        }
    }

    @Override
    @Transactional
    public boolean updateUser(User user) {
        User existingUser = userMapper.selectById(user.getId());
        if (existingUser == null) {
            return false;
        }

        return userMapper.update(user) > 0;
    }

    @Override
    @Transactional
    public boolean deleteUser(Integer id) {
        return userMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional
    public boolean resetPassword(String email) {
        logger.debug("开始执行密码重置: {}", email);
        User user = userMapper.selectByEmail(email);
        if (user == null) {
            logger.warn("邮箱不存在: {}", email);
            return false;
        }

        // 生成临时密码
        String tempPassword = generateTempPassword();
        logger.debug("为用户生成临时密码: {}", email);

        // 设置过期时间（24小时后）
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, 24);
        Date expireTime = calendar.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String expireTimeStr = sdf.format(expireTime);

        // 更新临时密码
        logger.debug("更新数据库中的临时密码: {}", email);
        boolean result = userMapper.updateTempPassword(email, tempPassword, expireTimeStr) > 0;

        if (result) {
            try {
                // 发送临时密码到邮箱
                logger.debug("开始发送临时密码到邮箱: {}", email);
                String subject = "密码重置";
                String content = "您的临时密码是：" + tempPassword + "，有效期为24小时。请登录后尽快修改您的密码。";
                emailUtil.sendEmail(email, subject, content);
                logger.info("密码重置邮件发送成功: {}", email);
            } catch (Exception e) {
                logger.error("发送邮件失败: {}, 错误: {}", email, e.getMessage(), e);
                // 发送邮件失败时，需要考虑是否回滚临时密码的更新
                // 这里我们选择不回滚，用户可以请求重新发送临时密码
            }
        } else {
            logger.warn("更新临时密码失败: {}", email);
        }

        return result;
    }

    @Override
    @Transactional
    public boolean changePassword(Integer id, String oldPassword, String newPassword) {
        User user = userMapper.selectById(id);
        if (user == null) {
            return false;
        }

        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return false;
        }

        // 加密新密码
        String encodedPassword = passwordEncoder.encode(newPassword);

        return userMapper.updatePassword(id, encodedPassword) > 0;
    }

    @Override
    @Transactional
    public boolean updateLockStatus(Integer id, Boolean locked) {
        return userMapper.updateLockStatus(id, locked) > 0;
    }

    @Override
    public boolean validateTempPassword(String email, String tempPassword) {
        User user = userMapper.selectByEmail(email);
        if (user == null || user.getTemporaryPassword() == null || user.getTempPasswordExpire() == null) {
            return false;
        }

        // 验证临时密码
        if (!user.getTemporaryPassword().equals(tempPassword)) {
            return false;
        }

        // 验证是否过期
        Date now = new Date();
        if (now.after(user.getTempPasswordExpire())) {
            return false;
        }

        return true;
    }

    /**
     * 生成8位随机临时密码
     */
    private String generateTempPassword() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < 8; i++) {
            int index = random.nextInt(chars.length());
            sb.append(chars.charAt(index));
        }

        return sb.toString();
    }
}
